package maven.diy;

import cn.hutool.core.io.file.FileReader;
import lombok.Data;
import maven.Scope;
import maven.TreeNode;

import java.util.*;

/**
 * @Author 史祥连
 * @Date 2024/2/1 16:32
 * @Version 1.0
 */

@Data
public class HandleResult {
    private static final String preFix = "";

    private long id;

    private String projectName;

    private String curTopProjectName;

    private Map<Integer, TreeNode> levelNodeMap = new HashMap<>();

    public HandleResult() {
    }

    public HandleResult(long id, String projectName) {
        this.id = id;
        this.projectName = projectName;
    }




    public TreeNode getTreeNode(String projectName) {
        TreeNode rootNode;
        FileReader fr;
        List<String> strings;
        fr = new FileReader("C:\\Datas\\maven\\weaver-ebuilder-form\\" + projectName + ".dependency");
        strings = fr.readLines();
        rootNode = new TreeNode();
        rootNode.setId(getAndAddId());
        rootNode.setJarName(projectName);
        rootNode.setProjectName(curTopProjectName);
        for (String string : strings) {
            handleNode(string, rootNode);
        }
        return rootNode;
    }

    public void handleNode(String currentInfo, TreeNode node) {
        TreeNode currentNode = new TreeNode();
        String[] infos = currentInfo.split(":");
        currentInfo = infos[0];
        String info = infos[1];
        int level = currentInfo.indexOf("+- ") / 3;
        currentNode.setVersion(infos[2]);
        currentNode.setGroup(infos[0].substring((level + 1) * 3));
        currentNode.setScope(getScope(infos[4]));
        currentNode.setProjectName(curTopProjectName);
        currentNode.setJarName(info);
        currentNode.setId(getAndAddId());
        currentNode.setKbSize(Long.parseLong(infos[5]));
        if (level > 0) {
            TreeNode parentNode = levelNodeMap.get(level - 1);
            currentNode.setParentId(parentNode.getId());
            List<TreeNode> treeNodes = Optional.ofNullable(parentNode.getTreeNodes()).orElse(new ArrayList<>());
            treeNodes.add(currentNode);
            parentNode.setTreeNodes(treeNodes);
        } else {
            List<TreeNode> treeNodes = Optional.ofNullable(node.getTreeNodes()).orElse(new ArrayList<>());
            treeNodes.add(currentNode);
            node.setTreeNodes(treeNodes);
        }
        levelNodeMap.put(level, currentNode);

    }


    private static Scope getScope(String info) {
        for (Scope value : Scope.values()) {
            if (info.endsWith(value.name())) {
                return value;
            }
        }
        return null;
    }

    private long getAndAddId() {
        return ++id;
    }





}
